use crate::config::config::ApplicationConfig;
use crate::config::option::Opt;
use clap::Parser;
use shared::ContextHelper;
use tokio::fs::read_to_string;

#[cfg(feature = "dev-tracing")]
use mf_core::tracing_init::dev_tracing::{init_tracing, TraceConfig};

pub async fn init_config() -> anyhow::Result<()> {
    let _ = build_config().await;
    let _ = init_logger();
    Ok(())
}

fn init_logger() -> anyhow::Result<()> {
    #[cfg(feature = "dev-tracing")]
    {
        let ref_app_config = ContextHelper::get::<ApplicationConfig>();
        let log_level = parse_log_level(ref_app_config.log().log_level());
        let log_dir = ref_app_config.log().log_dir();

        // 如果开启了 Chrome Tracing，使用 Chrome 格式
        #[cfg(feature = "dev-tracing-chrome")]
        let config = TraceConfig::chrome(format!("{}/trace.json", log_dir)).with_max_level(log_level);

        // 否则使用普通 JSON 格式
        #[cfg(not(feature = "dev-tracing-chrome"))]
        let config = TraceConfig::json(format!("{}/trace.json", log_dir)).with_max_level(log_level);

        let _guard = init_tracing(config)?;

        tracing::info!("📝 日志系统初始化完成");
        tracing::info!("📁 日志目录: {}", log_dir);
        tracing::info!("📊 日志级别: {:?}", log_level);

        #[cfg(feature = "dev-tracing-chrome")]
        tracing::info!("🌐 Chrome Tracing 已启用，请访问 chrome://tracing 查看");
    }

    #[cfg(not(feature = "dev-tracing"))]
    {
        // 生产环境：使用简单的 tracing_subscriber
        tracing_subscriber::fmt().with_max_level(tracing::Level::INFO).init();
    }

    Ok(())
}

/// 解析日志级别字符串
#[cfg(feature = "dev-tracing")]
fn parse_log_level(level: &str) -> tracing::Level {
    match level.to_lowercase().as_str() {
        "trace" => tracing::Level::TRACE,
        "debug" => tracing::Level::DEBUG,
        "info" => tracing::Level::INFO,
        "warn" => tracing::Level::WARN,
        "error" => tracing::Level::ERROR,
        _ => tracing::Level::INFO,
    }
}

async fn build_config() -> anyhow::Result<()> {
    let opt = Opt::parse();

    // 确定配置文件路径
    let config_path = if opt.config_path.is_empty() {
        #[cfg(debug_assertions)]
        {
            "./desktop-tauri/tauri/config.toml"
        }
        #[cfg(not(debug_assertions))]
        {
            "./config.toml"
        }
    } else {
        opt.config_path.as_str()
    };

    // 读取并解析配置文件
    let content = read_to_string(config_path).await.map_err(|e| anyhow::anyhow!("Failed to read config file at {}: {}", config_path, e))?;

    let config = ApplicationConfig::from_toml(&content);
    ContextHelper::set(config);
    Ok(())
}
